<template>
  <view class="sms-login-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>
    
    <!-- 登录表单 -->
    <view class="login-form">
      <!-- Logo区域 -->
      <view class="logo-section">
        <view class="logo">
          <text class="logo-text">短信验证码登录</text>
        </view>
        <text class="slogan">使用手机验证码快速登录</text>
      </view>
      
      <!-- 表单区域 -->
      <view class="form-section">
        <view class="form-item">
          <view class="input-wrapper">
            <text class="icon">📱</text>
            <input 
              class="input" 
              type="number" 
              placeholder="请输入手机号" 
              v-model="formData.phone"
              maxlength="11"
              @input="validatePhone"
            />
          </view>
          <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
        </view>
        
        <view class="form-item">
          <view class="input-wrapper">
            <text class="icon">🔐</text>
            <input 
              class="input" 
              type="number" 
              placeholder="请输入验证码" 
              v-model="formData.code"
              maxlength="4"
              @input="validateCode"
            />
            <button 
              class="code-btn" 
              :class="{ 'disabled': !canSendCode || codeSending }"
              :disabled="!canSendCode || codeSending"
              @click="sendCode"
            >
              {{ codeSending ? '发送中...' : codeText }}
            </button>
          </view>
          <text v-if="errors.code" class="error-text">{{ errors.code }}</text>
        </view>
        
        <!-- 登录按钮 -->
        <button 
          class="login-btn" 
          :class="{ 'disabled': !isFormValid || loading }"
          :disabled="!isFormValid || loading"
          @click="handleLogin"
        >
          <text v-if="loading" class="loading-text">登录中...</text>
          <text v-else>登录</text>
        </button>
        
        <!-- 其他登录方式 -->
        <view class="other-login">
          <view class="divider">
            <view class="line"></view>
            <text class="divider-text">其他登录方式</text>
            <view class="line"></view>
          </view>
          
          <view class="login-options">
            <button class="option-btn" @click="goToPasswordLogin">
              <text class="option-icon">🔒</text>
              <text class="option-text">密码登录</text>
            </button>
            
            <button class="option-btn" @click="goToRegister">
              <text class="option-icon">📝</text>
              <text class="option-text">注册账号</text>
            </button>
          </view>
        </view>
        
        <!-- 底部链接 -->
        <view class="bottom-links">
          <text class="link" @click="goToForgetPassword">忘记密码</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user.js'
import { SmsAPI } from '@/api/user.js'

// 使用用户store
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const codeSending = ref(false)
const countdown = ref(0)

// 表单数据
const formData = reactive({
  phone: '',
  code: ''
})

// 错误信息
const errors = reactive({
  phone: '',
  code: ''
})

// 表单验证
const validatePhone = () => {
  const phone = formData.phone
  if (!phone) {
    errors.phone = '请输入手机号'
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    errors.phone = '请输入正确的手机号'
    return false
  }
  errors.phone = ''
  return true
}

const validateCode = () => {
  const code = formData.code
  if (!code) {
    errors.code = '请输入验证码'
    return false
  }
  if (!/^\d{4}$/.test(code)) {
    errors.code = '验证码为4位数字'
    return false
  }
  errors.code = ''
  return true
}

// 是否可以发送验证码
const canSendCode = computed(() => {
  return formData.phone && !errors.phone && countdown.value === 0
})

// 验证码按钮文本
const codeText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}s` : '发送验证码'
})

// 表单是否有效
const isFormValid = computed(() => {
  return formData.phone && formData.code && !errors.phone && !errors.code
})

// 发送验证码
const sendCode = async () => {
  if (!canSendCode.value || codeSending.value) return
  
  // 验证手机号
  if (!validatePhone()) return
  
  codeSending.value = true
  
  try {
    const result = await SmsAPI.sendPhoneCode({ 
      phone: formData.phone,
      codeType: 1,
      type: 2
    })
    
    if (result.code === 0) {
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      })
      
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      uni.showToast({
        title: result.msg || '发送失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: error.message || '发送验证码失败',
      icon: 'none'
    })
  } finally {
    codeSending.value = false
  }
}

// 处理登录
const handleLogin = async () => {
  if (!isFormValid.value || loading.value) return
  
  // 验证表单
  const phoneValid = validatePhone()
  const codeValid = validateCode()
  
  if (!phoneValid || !codeValid) {
    return
  }
  
  loading.value = true
  
  try {
    await userStore.loginByCode({
      phone: formData.phone,
      accountType: 2,
      code: formData.code,
      codeType: 2
    })
    
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })
    
    // 延迟跳转，让用户看到成功提示
    setTimeout(() => {
      uni.reLaunch({
        url: '/views/index'
      })
    }, 1500)
  } catch (error) {
    console.error('登录失败:', error)
    uni.showToast({
      title: error.message || '登录失败，请检查网络连接',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 跳转到密码登录
const goToPasswordLogin = () => {
  uni.navigateBack()
}

// 跳转到注册页面
const goToRegister = () => {
  uni.navigateTo({
    url: '/views/register'
  })
}

// 跳转到忘记密码页面
const goToForgetPassword = () => {
  uni.navigateTo({
    url: '/views/forget-password'
  })
}

// 页面加载时检查是否已登录
onMounted(() => {
  // 检查登录状态
  if (userStore.isLoggedIn) {
    uni.reLaunch({
      url: '/views/index'
    })
  }
})
</script>

<style lang="scss" scoped>
.sms-login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

// 背景装饰
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  
  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    
    &.circle-1 {
      width: 200rpx;
      height: 200rpx;
      top: 10%;
      right: -50rpx;
    }
    
    &.circle-2 {
      width: 150rpx;
      height: 150rpx;
      top: 60%;
      left: -30rpx;
    }
    
    &.circle-3 {
      width: 100rpx;
      height: 100rpx;
      bottom: 20%;
      right: 20%;
    }
  }
}

.login-form {
  position: relative;
  z-index: 1;
  padding: 60rpx 40rpx;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

// Logo区域
.logo-section {
  text-align: center;
  margin-bottom: 80rpx;
  
  .logo {
    margin-bottom: 20rpx;
    
    .logo-text {
      font-size: 48rpx;
      font-weight: bold;
      color: #fff;
      text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
    }
  }
  
  .slogan {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

// 表单区域
.form-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
}

.form-item {
  margin-bottom: 40rpx;
  
  .input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 0 20rpx;
    border: 2rpx solid transparent;
    transition: all 0.3s ease;
    
    &:focus-within {
      border-color: #667eea;
      background: #fff;
      box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
    }
    
    .icon {
      font-size: 32rpx;
      margin-right: 20rpx;
      color: #666;
    }
    
    .input {
      flex: 1;
      height: 88rpx;
      font-size: 28rpx;
      color: #333;
      background: transparent;
      
      &::placeholder {
        color: #999;
      }
    }
    
    .code-btn {
      height: 60rpx;
      padding: 0 20rpx;
      background: #667eea;
      color: #fff;
      border: none;
      border-radius: 8rpx;
      font-size: 24rpx;
      margin-left: 20rpx;
      
      &.disabled {
        background: #ccc;
        color: #999;
      }
    }
  }
  
  .error-text {
    font-size: 24rpx;
    color: #ff4757;
    margin-top: 10rpx;
    display: block;
  }
}

// 登录按钮
.login-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12rpx;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
  transition: all 0.3s ease;
  
  &:not(.disabled):active {
    transform: scale(0.98);
  }
  
  &.disabled {
    background: #ccc;
    color: #999;
  }
  
  .loading-text {
    display: flex;
    align-items: center;
    justify-content: center;
    
    &::before {
      content: '';
      width: 20rpx;
      height: 20rpx;
      border: 2rpx solid #fff;
      border-top: 2rpx solid transparent;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-right: 10rpx;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 其他登录方式
.other-login {
  margin-bottom: 40rpx;
  
  .divider {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    
    .line {
      flex: 1;
      height: 1rpx;
      background: #e0e0e0;
    }
    
    .divider-text {
      padding: 0 20rpx;
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .login-options {
    display: flex;
    justify-content: space-around;
    
    .option-btn {
      flex: 1;
      margin: 0 10rpx;
      height: 80rpx;
      border: 2rpx solid #e0e0e0;
      border-radius: 12rpx;
      background: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.95);
        background: #f8f9fa;
      }
      
      .option-icon {
        font-size: 32rpx;
        margin-right: 10rpx;
      }
      
      .option-text {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

// 底部链接
.bottom-links {
  text-align: center;
  
  .link {
    font-size: 26rpx;
    color: #667eea;
    text-decoration: none;
    
    &:active {
      opacity: 0.7;
    }
  }
}
</style> 